package com.qd.pay.task;

import com.cdqidi.exception.ApiException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.kit.HttpKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class HttpNotify {
    private final ObjectMapper objectMapper;
    private final RestTemplate restTemplate;
    private static final String URL_START = "http";


    public void sendHttp(String notifyUrl, String notifyBody) {
        String result;
        try {
            if (notifyUrl.startsWith(URL_START)) {
                Map<String, String> heads = new HashMap<>(1);
                heads.put("Content-type", "application/json; charset=UTF-8");
                result = HttpKit.post(notifyUrl, notifyBody, heads);
            } else {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<>(notifyBody, headers);
                result = restTemplate.postForObject("http://" + notifyUrl, formEntity, String.class);
            }
            if (!StringUtils.hasLength(result)) {
                throw new ApiException("返回值为空");
            }
            authCode(result);
        } catch (Exception e) {
            throw new ApiException("请求发送失败，url: " + notifyUrl);
        }
    }

    private void authCode(String result) {
        try {
            final JsonNode resultNode = objectMapper.readTree(result);
            int code = resultNode.get("code").intValue();
            if (code != 1) {
                throw new ApiException("返回值异常，json: " + result);
            }
        } catch (JsonProcessingException e) {
            throw new ApiException("json转换失败，json: " + result);
        }
    }
}
